public class Solution {
    public String addBinary(String a, String b) {
        StringBuilder ret = new StringBuilder();
        int len1 = a.length();
        int len2 = b.length();
        StringBuilder temp = new StringBuilder();

        //空位补0
        if (len1 >= len2) {
            for (int i = 0; i < Math.abs(len1 - len2); i++) {
                temp.append('0');
            }
            temp.append(b);
            b = temp.toString();
        } else {
            for (int i = 0; i < Math.abs(len1 - len2); i++) {
                temp.append('0');
            }
            temp.append(a);
            a = temp.toString();
        }

        //转为int数组
        int len = Math.max(len1, len2);
        int[] A = new int[len];
        int[] B = new int[len];
        for (int i = 0; i < len; i++) {
            A[i] = a.charAt(i) - '0';
            B[i] = b.charAt(i) - '0';
        }

        //计算
        int t = 0;
        for (int i = len - 1; i >= 0; i--) {
            t += (A[i] + B[i]);
            ret.append(t % 2);//本位
            t /= 2;//进位
        }
        if (t == 0) {
            return ret.reverse().toString();//逆序
        } else {
            ret.append(t % 2);
            return ret.reverse().toString();
        }
    }
}
